import * as shell from 'shelljs';
// import path from 'path'

import { Config } from './types';
import { request } from './request';

export class LiveManger {
  private config: Config;
  private url: string;
  private onlineList: number[]

  constructor(cfg: Config) {
    this.config = cfg;
    this.url = 'http://api.live.bilibili.com/room/v1/Room/getRoomInfoOld';
    this.onlineList = []
  }

  private async getLiveInfo() {
    const { mid } = this.config;

    const res = [];

    await this.asyncForEach(mid, async (item: number) => {
      const data: any = await this.getRequestFromLive(item);

      data.data.data.id = item
      const a = data.data.data

      res.push(a);
    });
    return res;
  }

  private async watchRecorder() {
    const res = await this.getLiveInfo();

    for (const item of res) {
      if (item.liveStatus === 1) {
        if (this.onlineList.includes(item.id)) return
        this.runRecorder(item.roomid)

        this.onlineList.push(item.id)
      } else {
        if (this.onlineList.includes(item.id)) this.onlineList.filter(item.id)
      }
    }
  }

  public polling() {
    setInterval(async () => {
      await this.watchRecorder()
    }, 60 * 1000)
  }

  private runRecorder(id: number) {
    const dir = `${process.cwd()}/src/recorder/BiliLiveRecorder.jar`
    const command = `java -Dfile.encoding=utf-8 -jar ${dir} "debug=false&check=false&delete=false&qn=150&liver=bili&id=${id}&retry=5&"`;

    shell.exec(command);
  }

  private async getRequestFromLive(mid: number) {
    const url = `${this.url}?mid=${mid}`;
    const res = await request(url);
    // console.log(res);

    return res;
  }

  private async asyncForEach(array: number[], callback: Function) {
    for (let index = 0; index < array.length; index++) {
      await callback(array[index], index, array);
    }
  }
}
